﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Expression.Service;
using T.FAS.Runtime.ScheduleJob.SPI;
using T.ServiceComponent.Kernel.Service;
using  T.ServiceFramework.ServiceGateway.Client;

namespace T.FAS.Runtime.ScheduleJob.Engine
{
    public class DingDingGroupNoticeImpl : IScheduleJobSubscriptionNoticeHandler
    {
        public void Execute(ScheduleJobSubscription subscription, TResult result, ScheduleJobSubscriptionNoticeSet curNoticeSet)
        {
            //var executeResult = result.GetDataContent();
            SendMsgToDingDingGroup(subscription, curNoticeSet, result);
        }
        private void SendMsgToDingDingGroup(ScheduleJobSubscription subscription, ScheduleJobSubscriptionNoticeSet noticeSet, TResult result)
        {
            var sendMsg = noticeSet.NoticeContent;
            if (!string.IsNullOrEmpty(subscription.LinkUrl))
            {
                int subIndex = subscription.LinkUrl.IndexOf("&PlanId");
                if (subIndex > 0)
                {
                    subscription.LinkUrl = subscription.LinkUrl.Substring(0, subIndex);
                }
                subIndex = subscription.LinkUrl.IndexOf("?PlanId");
                if (subIndex > 0)
                {
                    subscription.LinkUrl = subscription.LinkUrl.Substring(0, subIndex);
                }
                if (subscription.LinkUrl.Contains("?"))
                    sendMsg = $"{sendMsg}\r\n\r\n[查看详情]({subscription.LinkUrl}&PlanId={subscription.SourceID})";
                else
                    sendMsg = $"{sendMsg}\r\n\r\n[查看详情]({subscription.LinkUrl}?PlanId={subscription.SourceID})";
            }
            sendMsg = NoticeHelper.SysParamReplace(sendMsg, subscription, result);
            var atPersonInfo = "";

            var mobileList = new List<string>();
            if (noticeSet.IsNeedAtPerson && !string.IsNullOrEmpty(noticeSet.PersonField))
            {
                SGHttpClient httpClient = new SGHttpClient(true);
                dynamic dataCollection = result;
                if (dataCollection.List != null && dataCollection.List.Count > 0)
                {
                    if (ConfigUtil.Instance.AuthUserId != "999")
                    {
                        var parameter = new Dictionary<string, string>();
                        var filter = new Dictionary<string, object>();
                        var filterKey = new { UserID = ConfigUtil.Instance.AuthUserId, Data_FunctionID = "DF686BBF-2387-4259-886B-249022156A8A", Enabled = 1 };
                        filter.Add("FieldName", "");
                        filter.Add("FilterKey", filterKey);
                        filter.Add("page", "1");
                        filter.Add("rows", "10");
                        foreach (dynamic dataItem in dataCollection.List)
                        {
                            var fieldValue = dataItem[noticeSet.PersonField];
                            string userName = Convert.ToString(fieldValue);
                            if (!string.IsNullOrEmpty(userName))
                                filter["FieldValue"] = userName;
                            parameter["filter"] = JsonConvert.SerializeObject(filter);
                            var response = httpClient.PostMainIDC<UserResult>("SYSMgr-ICommonService-GetUserList", parameter, 30);
                            if (response.state == "1" && response.data?.rows?.Count == 1)
                            {
                                if (mobileList.Contains("\"" + response.data.rows[0].Mobile + "\""))
                                    continue;
                                mobileList.Add("\"" + response.data.rows[0].Mobile + "\"");
                                atPersonInfo += "@" + response.data.rows[0].Mobile;
                            }
                            else
                            {
                                if (mobileList.Contains("\"" + userName + "\""))
                                    continue;
                                mobileList.Add("\"" + userName + "\"");
                                atPersonInfo += "@" + userName;
                            }
                        }
                    }
                    else
                    {
                        foreach (dynamic dataItem in dataCollection.List)
                        {
                            var fieldValue = dataItem[noticeSet.PersonField];
                            string userName = Convert.ToString(fieldValue);
                            if (mobileList.Contains("\"" + userName + "\""))
                                continue;
                            mobileList.Add("\"" + userName + "\"");
                            atPersonInfo += "@" + userName;
                        }
                    }
                }
                sendMsg += "\r\n\r\n负责人：" + atPersonInfo;
            }
            string jsContent = $"Funcs.SendMsgToGroup(title,sendMsg,[{string.Join(",", mobileList)}],'{noticeSet.TokenInfo}','{noticeSet.SecretInfo}',false)";
            var parameters = new Dictionary<string, object>();
            parameters.Add("title", subscription.Name);
            parameters.Add("sendMsg", sendMsg);
            //jsContent = jsContent.Replace("\r\n\r\n", "\\r\\n\\r\\n");
            var returnResult = ExprService.GetInstance.JSExecute(jsContent, parameters);
            if (returnResult.State == Expression.Entity.ResultState.Fail)
            {
                Base.Common.LogUtil.Log($"脚本：{jsContent}，失败原因：{returnResult.ErrMsg}", "ScheduleJob");
            }
        }


    }
}
